package com.atguigu.tingshu.live.service.impl;

import com.atguigu.tingshu.common.util.AuthContextHolder;
import com.atguigu.tingshu.live.config.LiveProperties;
import com.atguigu.tingshu.live.mapper.LiveRoomMapper;
import com.atguigu.tingshu.live.service.LiveRoomService;
import com.atguigu.tingshu.live.util.LiveAddressUtil;
import com.atguigu.tingshu.model.live.LiveRoom;
import com.atguigu.tingshu.vo.live.LiveRoomVo;
import com.atguigu.tingshu.vo.live.TencentLiveAddressVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
@SuppressWarnings({"unchecked", "rawtypes"})
public class LiveRoomServiceImpl extends ServiceImpl<LiveRoomMapper, LiveRoom> implements LiveRoomService {

	@Autowired
	private LiveRoomMapper liveRoomMapper;

	@Autowired
	private LiveProperties properties;

	@Autowired
	private LiveAddressUtil liveAddressUtil;

	@Override
	public LiveRoom saveLiveRoom(LiveRoomVo liveRoomVo) {
		//查询是否存在未过期的直播间,如果存在直接返回未过期的直播间
		Long userId = AuthContextHolder.getUserId();
		LiveRoom liveRoom = this.getOne(new LambdaQueryWrapper<LiveRoom>()
				.eq(LiveRoom::getUserId, userId)
				.gt(LiveRoom::getExpireTime, new Date()));
		//如果已经存在,则直接返回该直播间信息
		if (liveRoom != null){
			return liveRoom;
		}

		//不存在则新增
		liveRoom = new LiveRoom();
		BeanUtils.copyProperties(liveRoomVo, liveRoom);
		liveRoom.setUserId(userId);
		liveRoom.setAppName(properties.getAppName());
		String streamName = IdWorker.getIdStr();
		liveRoom.setStreamName(streamName);
		//获取推流地址和拉流地址
		TencentLiveAddressVo addressVo = liveAddressUtil.getLiveAddresses(streamName, liveRoomVo.getExpireTime());
		liveRoom.setPushUrl(addressVo.getPushWebRtcUrl());
		liveRoom.setPlayUrl(addressVo.getPullWebRtcUrl());
		this.save(liveRoom);
		return liveRoom;
	}
}
